import { DependencyContainer, HttpError, toSuccess, useEntityManager, useS3, useS3Preview } from "@sker/core"
import { useMulterS3 } from '@sker/multer-s3';
import { SysAttachment } from "@sker/entities";
import { z } from "zod";
import { useData } from "@sker/runtime";

export const upload = async (injector: DependencyContainer) => {
    const url = await useMulterS3(injector, async (file) => {
        return { url: file.location, key: file.key };
    })
    return toSuccess(url)
}

export const preview = async (injector: DependencyContainer) => {
    const input = z.object({
        key: z.string(),
    })
    const body = input.parse(useData())
    return previewOne(body.key)
}

export const previews = async (injector: DependencyContainer) => {
    const input = z.object({
        keys: z.any()
    })
    const body = input.parse(useData())
    const keys = body.keys;
    if (Array.isArray(keys)) {
        const urls = await Promise.all(keys.filter(it=>!!it).map(async key => await previewOne(key)))
        return urls;
    }
    if (typeof keys === 'string') {
        return await Promise.all(keys.split(',').filter(it=>!!it).map(async key => await previewOne(key)))
    }
    throw new HttpError(`参数keys:${keys}不支持`)
}

const previewOne = async (key: string) => {
    if (key.startsWith('http')) return key;
    if (key.startsWith('/')) return key;
    if (key.startsWith('./')) return key;
    const attachment = await useEntityManager(async m => {
        const attachment = await m.findOne(SysAttachment, { where: { hash: key } })
        if (attachment) return attachment;
        return;
    })
    if (attachment) {
        if (attachment.from === 's3') {
            return useS3Preview(key)
        } else {
            return attachment.url;
        }
    }
    return useS3Preview(key)
}